package cn.grayrelese.filter;

import javax.servlet.http.HttpServletRequest;

import cn.grayrelese.entity.ConfigParameter;
import cn.grayrelese.entity.User;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.ZuulFilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

/**
 * 灰度校验拦截器
 */
public class GrayReleseFilter extends ZuulFilter {
//    @Value("#{'${grayrelese.users1}'.split(',')}")
//    private List<String> users1;
    @Autowired
    private ConfigParameter config;
    private static Logger log = LoggerFactory.getLogger(GrayReleseFilter.class);

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("accessToken");
//        log.info("accessToken="+accessToken);
        //校验token
        User user = checkToken(accessToken);
        if (user!=null) {
            log.info("access token ok："+accessToken);
            //第一种方式加请求头
            request.setAttribute("version",user.getVersion());
            //设置转发参数
            context.addZuulRequestHeader("user", JSONObject.toJSONString(user));
            context.addZuulRequestHeader("version",user.getVersion());
            return null;
        }
        log.warn("access token is null or error!");
        return null;
    }

    /**
     * 校验token 返回用户信息
     * @param accessToken
     * @return
     */
    private User checkToken(Object accessToken) {
        if(accessToken!=null&&config!=null&&config.users!=null){
            List<User> users = config.users;
            for (User user: users) {
                if(accessToken.equals(user.getName()))
                    return user;
            }
        }
        return null;
    }
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }

}